package com.smcdd.cdb.dbo.cdb_dbo.service.presenter;

import android.content.Intent;
import android.util.Log;
import android.widget.ListView;
import android.widget.PopupMenu;

import com.smcdd.cdb.dbo.cdb_dbo.app.App;
import com.smcdd.cdb.dbo.cdb_dbo.network.HttpObserver;
import com.smcdd.cdb.dbo.cdb_dbo.network.factory.RetrofitFactory;
import com.smcdd.cdb.dbo.cdb_dbo.service.entity.BaseResponseEntity;
import com.smcdd.cdb.dbo.cdb_dbo.service.entity.ContactBean;
import com.smcdd.cdb.dbo.cdb_dbo.service.entity.StoreInfo;
import com.smcdd.cdb.dbo.cdb_dbo.service.entity.StoreInfoV2;
import com.smcdd.cdb.dbo.cdb_dbo.service.maneger.DataManager;
import com.smcdd.cdb.dbo.cdb_dbo.service.maneger.NetWorkCodeInfo;
import com.smcdd.cdb.dbo.cdb_dbo.service.view.IQueryAc;
import com.smcdd.cdb.dbo.cdb_dbo.ui.adapter.SortAdapter;
import com.smcdd.cdb.dbo.cdb_dbo.ui.base.BaseActivity;
import com.smcdd.cdb.dbo.cdb_dbo.ui.base.BasePresenter;
import com.smcdd.cdb.dbo.cdb_dbo.ui.utils.CharacterParser;
import com.smcdd.cdb.dbo.cdb_dbo.ui.utils.ObtainEncry;
import com.smcdd.cdb.dbo.cdb_dbo.ui.utils.ObtainVersion;
import com.smcdd.cdb.dbo.cdb_dbo.ui.utils.PinyinComparator;
import com.smcdd.cdb.dbo.cdb_dbo.ui.widget.SideBar;

import java.util.ArrayList;
import java.util.Collections;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import rx.Observer;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;
import rx.subscriptions.CompositeSubscription;

/**
 * 作者：Administrator on 2017/6/28 11:26
 * 邮箱：zhanghuaiha@gmail.com
 */

public class QueryPresenter extends BasePresenter<IQueryAc> {

    private DataManager manager;
    private String id;
    private CompositeSubscription mCompositeSubscription;
    private String udid;
    private String versionName;
    private String eid;
    private SortAdapter adapter;
    private List<StoreInfoV2> SourceDateList;
    private CharacterParser characterParser;
    private PinyinComparator pinyinComparator;
    private ListView listView;
    private String temporary = "A";
    private List<StoreInfoV2> data;
    private static final int REQUEST_SEARCH_CODE = 1;

    public QueryPresenter(BaseActivity context) {
        super(context);
    }

    public void loadContacts(String udid){
        this.udid = udid;
        // 实例化汉字转拼音类
        characterParser = CharacterParser.getInstance();
        pinyinComparator = new PinyinComparator();
        manager = new DataManager(mContext);
        versionName = ObtainVersion.getVersionName(mContext);
        id = App.SP.getString("id", "");
        mCompositeSubscription = new CompositeSubscription();
        setAdapter();
        // loadData();
        loadNetWork(udid);
    }

    public void unLoadData(){
        if (mCompositeSubscription.hasSubscriptions()){
            mCompositeSubscription.unsubscribe();
        }
    }

    private void setAdapter() {
        listView = getView().getListView();
        SideBar mSidebar = getView().getSideBar();

        mSidebar.setOnTouchingLetterChangedListener(s -> {
            // 该字母首次出现的位置
            if (s.equals("☆")){
                s = "A";
            }
            if (temporary.equals(s)) {
                return;
            }
            if (s.equals("↑")) {
                listView.setSelection(0);
            }
            int position = adapter.getPositionForSection(s.charAt(0));
            if (position != -1) {
                listView.setSelection(position);
            }
            temporary = s;
        });
        //listview条目点击事件
        listView.setOnItemClickListener((parent, view, position, id) -> {
            StoreInfoV2 item = (StoreInfoV2) adapter.getItem(position);
            Intent intent = new Intent();
            intent.putExtra("id",item.getId());
            intent.putExtra("name",item.getName());
            Log.e("QueryPresenter",item.getName()+"!!!!"+position);
            mContext.setResult(REQUEST_SEARCH_CODE,intent);
            mContext.finish();

        });
    }


    /**
     * 为ListView填充数据
     *
     * @param date
     * @return`
     */
    private List<StoreInfoV2> filledData(List<StoreInfoV2> date) {
        List<StoreInfoV2> mSortList = new ArrayList<>();

        for (int i = 0; i < date.size(); i++) {
            StoreInfoV2 sortModel = new StoreInfoV2();
            sortModel.setName(date.get(i).getName());
            sortModel.setImg_url(date.get(i).getImg_url());
            sortModel.setId(date.get(i).getId());
            sortModel.setStore_type(date.get(i).getStore_type());
            // 汉字转换成拼音
            String pinyin = characterParser.getSelling(date.get(i).getName());
            String sortString = pinyin.substring(0, 1).toUpperCase();

            // 正则表达式，判断首字母是否是英文字母
            if (sortString.matches("[A-Z]")) {
                sortModel.setSortLetters(sortString.toUpperCase());
            } else {
                sortModel.setSortLetters("#");
            }

            mSortList.add(sortModel);
        }
        return mSortList;
    }


    private void loadNetWork(String udid) {
        eid = App.SP.getString("id", "");
        String tiem = System.currentTimeMillis() + "";
        Map<String,String> map = new LinkedHashMap<>();
        map.put("rf","2");
        map.put("ts",tiem);
        map.put("v",versionName);
        map.put("i",NetWorkCodeInfo.STORE);
        map.put("udid",udid);
        map.put("eid",eid);
        map.put("page_size","10000");
        map.put("page_index","0");
        String encry1 = ObtainEncry.getEncry(map);
        map.put("encry",encry1);
        RetrofitFactory.getmInstanse().mApi.getStoreInfos(map)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new HttpObserver<BaseResponseEntity<List<StoreInfoV2>>>() {
                    @Override
                    public void success(BaseResponseEntity<List<StoreInfoV2>> listBaseResponseEntity) {
                        if (listBaseResponseEntity.code == 200) {
                            List<StoreInfoV2> data = listBaseResponseEntity.data;

//                            List<StoreInfoV2> list = new ArrayList<>();
//                            for (int i = 0; i < data.size(); i++) {
//                                if (data.get(i).getStatus().equals("1")) {
//                                    list.add(data.get(i));
//                                }
//                            }
                            SourceDateList = filledData(data);
                            // 根据a-z进行排序源数据
                            Collections.sort(SourceDateList, pinyinComparator);
                            adapter = new SortAdapter(mContext, SourceDateList);
                            listView.setAdapter(adapter);
                        }
                    }

                    @Override
                    public void onError(Throwable e) {
                        super.onError(e);
                    }
                });

//        String encry = ObtainEncry.getStoreInfo("2", time, versionName, NetWorkCodeInfo.STORE, udid, eid, "10000", "0");
//        mCompositeSubscription.add(manager.getStoreInfos("2",time, versionName, NetWorkCodeInfo.STORE, udid, eid,"10000","0",encry)
//                .subscribeOn(Schedulers.io())
//                .observeOn(AndroidSchedulers.mainThread())
//                .subscribe(new Observer<StoreInfo>() {
//                    @Override
//                    public void onCompleted() {
//
//                    }
//
//                    @Override
//                    public void onError(Throwable e) {
//
//                    }
//
//                    @Override
//                    public void onNext(StoreInfo storeInfo) {
//                        Log.e("QueryPresenter",storeInfo.getCode()+"");
//                        if (storeInfo.getCode() == 200) {
//                            data = storeInfo.getData();
//                            List<StoreInfo.DataBean> list = new ArrayList<StoreInfo.DataBean>();
//                            for (int i = 0; i < data.size(); i++) {
//                                if (data.get(i).getStatus().equals("1")) {
//                                    list.add(data.get(i));
//                                }
//                            }
//                            SourceDateList = filledData(list);
//                            // 根据a-z进行排序源数据
//                            Collections.sort(SourceDateList, pinyinComparator);
//                            adapter = new SortAdapter(mContext, SourceDateList);
//                            listView.setAdapter(adapter);
//                        }
//                    }
//                }));
    }
}
